package com.cnblogs.leizia.crm.workbench.web.controller;

import com.cnblogs.leizia.crm.commen.ErrorCode;
import com.cnblogs.leizia.crm.commen.RequestUri;
import com.cnblogs.leizia.crm.commen.Result;
import com.cnblogs.leizia.crm.exception.ClueException;
import com.cnblogs.leizia.crm.settings.domain.User;
import com.cnblogs.leizia.crm.utils.DateTimeUtil;
import com.cnblogs.leizia.crm.utils.PrintJson;
import com.cnblogs.leizia.crm.utils.ServiceFactory;
import com.cnblogs.leizia.crm.utils.UUIDUtil;
import com.cnblogs.leizia.crm.workbench.domain.Activity;
import com.cnblogs.leizia.crm.workbench.domain.Clue;
import com.cnblogs.leizia.crm.workbench.domain.Tran;
import com.cnblogs.leizia.crm.workbench.service.ActivityService;
import com.cnblogs.leizia.crm.workbench.service.ClueService;
import com.cnblogs.leizia.crm.workbench.service.impl.ActivityServiceImpl;
import com.cnblogs.leizia.crm.workbench.service.impl.ClueServiceImpl;
import com.mysql.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 线索控制器
 *
 * @author leizi
 * @create 2021-03-02 22:28
 */
public class ClueController extends HttpServlet {

    private ClueService clueService = (ClueService) ServiceFactory.getService(new ClueServiceImpl());
    private ActivityService activityService = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();

        // 获取所有者用户列表
        if (RequestUri.CLUE_GET_USER_LIST.getUriPath().equals(path)) {
            getUserList(req, resp);
        }
        // 保存线索
        if (RequestUri.CLUE_SAVE.getUriPath().equals(path)) {
            saveClue(req, resp);
        }
        // 分页获取线索列表
        if (RequestUri.CLUE_PAGE_LIST.getUriPath().equals(path)) {
            getPageList(req, resp);
        }
        // 跳转线索详情页
        if (RequestUri.CLUE_DETAIL.getUriPath().equals(path)) {
            dispatcherDetail(req, resp);
        }
        // 获取线索关联的市场活动列表
        if (RequestUri.CLUE_GET_ACTIVITY_LIST.getUriPath().equals(path)) {
            getActivityList(req, resp);
        }
        if (RequestUri.CLUE_UNRELEVANCE.getUriPath().equals(path)) {
            clueActivityUnRelevance(req, resp);
        }
        if (RequestUri.CLUE_ACTIVITYLIST.getUriPath().equals(path)) {
            getClueActivityList(req, resp);
        }
        if (RequestUri.CLUE_SAVE_RELEVANCE.getUriPath().equals(path)) {
            saveRelevance(req, resp);
        }
        if (RequestUri.CLUE_SEARCH_ACTIVITYLIST.getUriPath().equals(path)) {
            searchActivityList(req, resp);
        }
        if (RequestUri.CLUE_CONVERT.getUriPath().equals(path)) {
            clueConvert(req, resp);
        }
    }

    /**
     * 线索转换为联系人、客户和交易
     *
     * @param request
     * @param response
     * @return
     */
    private Result clueConvert(HttpServletRequest request, HttpServletResponse response) {

        String clueId = request.getParameter("clueId");
        Tran tran = null;

        String flag = request.getParameter("flag");
        //判断标志位是否需要为客户创建交易
        if (!StringUtils.isNullOrEmpty(flag)) {
            String money = request.getParameter("money");
            String name = request.getParameter("name");
            String expectDate = request.getParameter("expectDate");
            String stage = request.getParameter("stage");
            String activityId = request.getParameter("activityId");

            tran = new Tran();

            tran.setMoney(money);
            tran.setName(name);
            tran.setExpectedDate(expectDate);
            tran.setStage(stage);
            tran.setActivityId(activityId);
        }

        activityService.clueConvert(clueId, tran);

        // 重定向到线索列表页
        try {
            response.sendRedirect(request.getContextPath() + "/workbench/clue/index.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 线索转换搜索市场活动列表
     *
     * @param request
     * @param response
     * @return
     */
    private Result searchActivityList(HttpServletRequest request, HttpServletResponse response) {

        String name = request.getParameter("name");
        List<Activity> clueActivityList = activityService.getClueActivityList(name, null);

        PrintJson.printJsonObj(response, Result.successToDataResult(clueActivityList));

        return null;
    }

    /**
     * 添加线索与市场活动关系
     *
     * @param request
     * @param response
     * @return
     */
    private Result saveRelevance(HttpServletRequest request, HttpServletResponse response) {

        String clueId = request.getParameter("clueId");
        String activityIds = request.getParameter("activityIds");
        // 线索与市场活动关联关系表添加记录
//        boolean result = clueService.saveRelevance(clueId, activityIds);


        return null;
    }

    /**
     * 根据条件查询且排除已关联的市场活动
     *
     * @param request
     * @param response
     * @return
     */
    private Result getClueActivityList(HttpServletRequest request, HttpServletResponse response) {

        String name = request.getParameter("name");
        String clueId = request.getParameter("clueId");

        // 根据线索id查询关联的市场活动
        List<Activity> activities = clueService.getActivityListById(clueId);

        // 根据条件查询且排除已关联的市场活动
        List<Activity> clueActivityList = activityService.getClueActivityList(name, activities);

        PrintJson.printJsonObj(response, Result.successToDataResult(clueActivityList));

        return null;
    }

    /**
     * 解除关联
     *
     * @param request
     * @param response
     * @return
     */
    private Result clueActivityUnRelevance(HttpServletRequest request, HttpServletResponse response) {
        String relevanceId = request.getParameter("relevanceId");

        boolean relevance = clueService.clueActivityUnRelevance(relevanceId);
        if (relevance) {
            PrintJson.printJsonFlag(response, true);
        } else {
            PrintJson.printJsonObj(response, Result.errorResult(ErrorCode.CLUE_UNRELEVANCE.getMsg()));
        }

        return null;
    }

    /**
     * 获取线索关联的市场活动列表
     *
     * @param request
     * @param response
     * @return
     */
    private Result getActivityList(HttpServletRequest request, HttpServletResponse response) {
        String clueId = request.getParameter("clueId");
        if (StringUtils.isNullOrEmpty(clueId)) {
            PrintJson.printJsonObj(response, Result.errorResult(ErrorCode.PARAM_FAIL.getMsg()));
        }
        // 查询线索与市场活动关联表
        List<Activity> activityList = clueService.getActivityList(clueId);

        PrintJson.printJsonObj(response, Result.successToDataResult(activityList));

        return null;
    }

    /**
     * 跳转线索详情页
     *
     * @param request
     * @param response
     * @return
     */
    private Result dispatcherDetail(HttpServletRequest request, HttpServletResponse response) {
        String clueId = request.getParameter("clueId");
        Clue clue = clueService.dispatcherDetail(clueId);

        request.setAttribute("clue", clue);
        try {
            // 转发到线索详情页，局部刷新所以用转发
            request.getRequestDispatcher("/workbench/clue/detail.jsp").forward(request, response);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
            PrintJson.printJsonObj(response, Result.errorResult(ErrorCode.DISPATCHER.getMsg()));
        }


        return null;
    }

    /**
     * 分页获取线索列表
     *
     * @param request
     * @param response
     * @return
     */
    private Result getPageList(HttpServletRequest request, HttpServletResponse response) {

        String pageNo = request.getParameter("pageNo");
        String pageSize = request.getParameter("pageSize");
        // 权限控制
        User user = (User) request.getSession().getAttribute("user");
        // 当前登录用户id
        String loginUserId = user.getId();
        Map<String, Object> map = new HashMap<>();
        map.put("pageNo", Integer.valueOf(pageNo));
        map.put("pageSize", Integer.valueOf(pageSize));
        map.put("owner", loginUserId);
        List<Clue> clueList = clueService.getPageList(map);

        PrintJson.printJsonObj(response, Result.successToDataResult(clueList));

        return null;
    }

    /**
     * 保存线索
     *
     * @param request
     * @param response
     * @return
     */
    private Result saveClue(HttpServletRequest request, HttpServletResponse response) {

        Clue clue = new Clue();
        clue.setId(UUIDUtil.getUUID());
        clue.setFullname(request.getParameter("fullname"));
        clue.setAppellation(request.getParameter("appellation"));
        clue.setOwner(request.getParameter("owner"));
        clue.setCompany(request.getParameter("company"));
        clue.setJob(request.getParameter("job"));
        clue.setEmail(request.getParameter("email"));
        clue.setPhone(request.getParameter("phone"));
        clue.setWebsite(request.getParameter("website"));
        clue.setMphone(request.getParameter("mphone"));
        clue.setState(request.getParameter("state"));
        clue.setSource(request.getParameter("source"));
        clue.setDescription(request.getParameter("description"));
        clue.setContactSummary(request.getParameter("contactSummary"));
        clue.setNextContactTime(request.getParameter("nextContactTime"));
        clue.setAddress(request.getParameter("address"));
        clue.setCreateTime(DateTimeUtil.getSysTime());
        User user = (User) request.getSession().getAttribute("user");
        clue.setCreateBy(user.getName());

        boolean saveSuccess = clueService.saveClue(clue);
        if (saveSuccess) {
            PrintJson.printJsonObj(response, Result.successResult());
        } else {
            PrintJson.printJsonObj(response, Result.errorResult(ErrorCode.CLUE_SAVE_ERROR.getMsg()));
        }

        return null;
    }

    /**
     * 获取创建线索所有者列表
     *
     * @param request
     * @param response
     * @return
     */
    private Result getUserList(HttpServletRequest request, HttpServletResponse response) {

        try {
            List<User> userList = clueService.getUserList();

            PrintJson.printJsonObj(response, Result.successToDataResult(userList));
        } catch (ClueException e) {
            e.printStackTrace();
            PrintJson.printJsonObj(response, Result.errorResult(e.getMessage()));
        }

        return null;
    }
}
